package com.lihaozhe.service;

import com.lihaozhe.commons.result.ResultCode;
import com.lihaozhe.commons.string.StringUtil;
import com.lihaozhe.dto.Role;
import com.lihaozhe.dto.SecUser;
import com.lihaozhe.mapper.RoleMapper;
import com.lihaozhe.mapper.SecUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/12/8 上午10:05
 */
@Service
@RequiredArgsConstructor
public class UserService implements UserDetailsService {
    private final PasswordEncoder passwordEncoder;
    private final SecUserMapper userMapper;
    private final RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtil.isBlank(username)) {
            throw new UsernameNotFoundException(ResultCode.ACCOUNT_ISNULL.getMsg());
        }
        SecUser user = userMapper.selectByUsername(username);
        List<Role> roles = roleMapper.selectByUid(user.getId());
        String password = passwordEncoder.encode(user.getPassword());
        if (roles == null) {
            return new User(username, password, AuthorityUtils.createAuthorityList());
        }
        List<GrantedAuthority> roleNames = roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
        return new User(username, password, roleNames);
    }
}